package com.dianban.controller;

import com.dianban.base.ResultCode;
import com.dianban.base.ResultVo;
import com.dianban.entity.FacePayConfig;
import com.dianban.entity.FacePayStoreOrder;
import com.dianban.entity.ShopUser;
import com.dianban.entity.User;
import com.dianban.plugin.weixinpay.LeshuaPayFacePlugin;
import com.dianban.plugin.weixinpay.WeixinPayFacePlugin;
import com.dianban.service.*;
import com.dianban.utils.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;

/**
 * @author wujh
 * @create 2020/1/10
 */
@Api(value = "ApiLeshuaPayController", description = "乐刷支付控制器")
@RestController
@RequestMapping(value = "${interfacePath}/leshuan/")
public class ApiLeshuaPayController extends BaseController {

    @Autowired
    private LeshuaPayFacePlugin leshuaPayFacePlugin;
    @Autowired
    private UserService userService;
    @Autowired
    private FacePayStoreOrderService facePayStoreOrderService;
    @Autowired
    private FacePayCommissionLogService facePayCommissionLogService;
    @Autowired
    private FacePayConfigService facePayConfigService;

    @ApiOperation(notes = "getWxpayfaceCodeParams", httpMethod = "POST", value = "进行人脸识别参数")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "screenMac", value = "屏幕Mac", required = true, paramType = "header",dataType = "string"),
            @ApiImplicitParam(name = "shopUserToken", value = "商户用户token", required = true, paramType = "header",dataType = "string"),
            @ApiImplicitParam(name = "rawdata", value = "初始化数据", required = true, paramType = "query",dataType = "string"),
    })
    @RequestMapping(value = "getWxpayfaceCodeParams",method = RequestMethod.POST)
    public ResultVo get_wxpayface_authinfo(String rawdata, HttpServletRequest request, HttpServletResponse response) {
        if(StringUtils.isEmpty(rawdata)){
            return ResultVo.error(ResultCode.ERROR,"初始化数据不能为空");
        }
        ShopUser shopUser = UserUtils.getShopUser(request);
        String screenMac = UserUtils.getScreenMac(request);
        String store_id = shopUser.getStoreId().toString();
        String device_id = shopUser.getStoreId().toString();
        String store_name= StringUtils.isBlank(shopUser.getNickname())? "门店名称":shopUser.getNickname();

        ResultVo resultvo = leshuaPayFacePlugin.getWxpayfaceAuthinfo( store_id, store_name, device_id, rawdata,screenMac);
        if(!"200".equals(resultvo.getCode())){
            return resultvo;
        }
        HashMap<String, Object> resultMape = ( HashMap<String, Object>)resultvo.getContent();
        String authinfo = (String)resultMape.get("auth_info");
        HashMap<String, Object> params = leshuaPayFacePlugin.getWxpayfaceCodeParams( store_id, authinfo);
        return ResultVo.success(params,"操作成功");
    }

    @ApiOperation(notes = "micropay", httpMethod = "POST", value = "进行发起订单支付")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "screenMac", value = "屏幕Mac", required = true, paramType = "header",dataType = "string"),
            @ApiImplicitParam(name = "shopUserToken", value = "门店用户token", required = true, paramType = "header",dataType = "string"),
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "out_trade_no", value = "订单号", required = false, paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "total_fee", value = "订单总金额，单位为分，只能为整数", required = false, paramType = "query",dataType = "Integer"),
            @ApiImplicitParam(name = "face_code", value = "人脸凭证", required = true, paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "spbill_create_ip", value = "调用微信支付API的机器IP", required = true, paramType = "query",dataType = "string"),

    })
    @RequestMapping(value = "micropay",method = RequestMethod.POST)
    public ResultVo micropay(Long userId,String out_trade_no,String face_code,String spbill_create_ip ,Integer total_fee,HttpServletRequest request, HttpServletResponse response) {
        if(StringUtils.isBlank(face_code)){
            return ResultVo.error(ResultCode.ERROR,"人脸凭证不能为空");
        }
        if(StringUtils.isBlank(spbill_create_ip)){
            return ResultVo.error(ResultCode.ERROR,"机器IP不能为空");
        }
        if (userId == null) {
            return ResultVo.error(ResultCode.ERROR, "用户id不能为空");
        }
        User user = userService.findById(userId);
        if (user == null) {
            return ResultVo.error(ResultCode.ERROR, "用户id错误");
        }
        if(total_fee == null){
            return ResultVo.error(ResultCode.ERROR,"订单总金额不能为空");
        }
        ShopUser shopUser = UserUtils.getShopUser(request);
        Long shopUserId = shopUser.getId();
        Long storeId = shopUser.getStoreId();
        String store_name= StringUtils.isBlank(shopUser.getNickname())? "门店名称":shopUser.getNickname();
        String body = store_name;
        if(StringUtils.isBlank(out_trade_no)){
            return ResultVo.error(ResultCode.ERROR,"订单号不能为空");
        }
        FacePayStoreOrder facePayStoreOrder = facePayStoreOrderService.findByOrderNumber(out_trade_no);
        if(facePayStoreOrder == null){
            return ResultVo.error(ResultCode.ERROR,"订单号错误");
        }
        BigDecimal money = facePayStoreOrder.getMoney();
        total_fee = money.multiply(new BigDecimal(100)).intValue();
        if (total_fee == 0) {
            return ResultVo.error(ResultCode.ERROR,"订单支付金额错误");
        }
        ResultVo resultVo = leshuaPayFacePlugin.micropay( storeId.toString(), body,out_trade_no,total_fee, spbill_create_ip,face_code);
        if(resultVo.getCode().equals(ResultCode.SUCESS.getCode())){
            int count = facePayStoreOrderService.updateStateAndCommission(facePayStoreOrder);
        }
        return resultVo;
    }

    @RequestMapping(value = "/asyncNotify/{sn}")
    public String asyncNotify(@PathVariable String sn, HttpServletRequest request) {
        String result = "";
        try {
            if (StringUtils.isBlank(sn)) {
                return result;
            }
            FacePayStoreOrder facePayStoreOrder = facePayStoreOrderService.findByOrderNumber(sn);
            if (facePayStoreOrder == null) {
                return result;
            }
            if (20 == facePayStoreOrder.getPayStatus()) {
                return leshuaPayFacePlugin.getNotifyMessage();
            }
            String tradeSn = leshuaPayFacePlugin.verifyNotify(sn, facePayStoreOrder.getMoney(), request);
            if (StringUtils.isNotBlank(tradeSn)) {
                int count = facePayStoreOrderService.updateStateAndCommission(facePayStoreOrder);
                if (count == 1) {
                    return leshuaPayFacePlugin.getNotifyMessage();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        }
        return result;
    }

}
